import 'package:flutter/material.dart';
import 'package:xm_app/common/ui/ui_adapter.dart';

///星星评分组件
class StarRating extends StatelessWidget {
  final double maxRating;
  final double rating;
  final int starCount;
  final double size;
  final Color unColor;
  final Color onColor;
  const StarRating({
    Key key,
    this.maxRating = 10,
    this.starCount = 5,
    this.rating = 0,
    this.size = 13,
    this.unColor = Colors.grey,
    this.onColor = const Color(0xFFFBC02D),
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Stack(
      children: [
        Row(
          children: [
            ..._buildUnStar(),
          ],
        ),
        Row(
          children: [
            ..._buildOnStar(),
          ],
        ),
      ],
    ));
  }

  List<Widget> _buildUnStar() {
    return List.generate(starCount, (index) => _buildStar(unColor, size));
  }

  List<Widget> _buildOnStar() {
    //1.计算Star个数和剩余比例等
    List<Widget> onList = List();
    double oneVale = maxRating / starCount;
    int entireCount = (rating / oneVale).floor();
    double leftValue = rating - entireCount * oneVale;
    double leftRatio = leftValue / oneVale;
    //2.获取Star
    List<Widget> selectedImages = [];
    for (int i = 0; i < entireCount; i++) {
      onList.add(_buildStar(onColor, size));
    }
    //3.计算
    Widget leftStar = ClipRect(
      clipper: MyRectClipper(width: leftRatio * size),
      child: _buildStar(onColor, size),
    );
    onList.add(leftStar);
    return onList;
  }

  Widget _buildStar(Color color, double starSize) {
    return Icon(
      Icons.star,
      size: starSize,
      color: color,
    );
  }
}

class MyRectClipper extends CustomClipper<Rect> {
  final double width;

  MyRectClipper({this.width});

  @override
  Rect getClip(Size size) {
    return Rect.fromLTRB(0, 0, width, size.height);
  }

  @override
  bool shouldReclip(MyRectClipper oldClipper) {
    return width != oldClipper.width;
  }
}
